<template>
	<view class="indexpage">
		<view class="kehu">
			<nav-bar :cityName="cityName" :district="district"></nav-bar>
			<!-- banner -->
			<ban-ner></ban-ner>
			<menu-list></menu-list>
			<!-- xiaohaibao -->
			<view class="sban" >
				<image  src="https://mini-one-1258127031.cos.ap-chengdu.myqcloud.com/1%E5%8F%B7%E5%AE%B6%E5%B8%AE/APPbanner%E7%AB%8B%E5%8D%B3%E9%A2%84%E7%BA%A6.png" mode=""></image>
			</view>
			
			<!-- 服务列表 客户显示 -->
			<!-- v-if="classd == 1 " -->
			<view class="list-free" v-if="classd == 1 " >  
				<view class="good">
					<text class="title">优质商家</text>
				</view>
				<shop-list ></shop-list>
			</view>
			<!-- 技工接单列表  商家或技工显示 -->
			<view class="list-free" v-if="classd == 2">
				<view class="good">
					<text class="title">接单中心</text>
				</view>
				<!-- <shop-list v-if="classd == 1"></shop-list> -->
				<order-list ref="order" :dialogData="dialogData" :dialog="dialog" :formData="formData" @orderChange="orderChange" @doneOrderid="doneOrderid"></order-list>
			</view>
		</view>

		
		
		
		<!-- 报价 -->
		<view class="baojia">
			<van-dialog
			  use-slot
			  title="订单报价"
			  :show="dialog.show"
			  show-cancel-button
			  @cancel="close"
			  @confirm="getSetting"
			>
			  <view class="order_info">
				  
			  	<van-field label="服务项目"
			  	:value="formData.name" 
			  	type="number" 
				disabled
			  	left-icon="orders-o" clearable  ></van-field>
				
				<van-field label="发布者"
				:value="formData.username" 
				type="number" 
				disabled
				left-icon="user-o" clearable  ></van-field>
				
				<van-field label="订单报价"
				:value="formData.orderprice" 
				type="digit" 
				left-icon="location-o" @change="priceChange" clearable placeholder="请输入报价"  ></van-field>
				
				<van-field label="预付金额"
				:value="formData.imprest" 
				type="digit" 
				left-icon="location-o" @change="imprestChange" clearable placeholder="请输入预付金额"  ></van-field>
				
			  </view>
			</van-dialog>
		</view>
		
		<!-- 拨打电话 -->
		<view class="makephone" @click="makephone">
			<text class="iconfont icon-shouji"></text>
		</view>
		<!-- yijia -->
		<!-- dialog -->
		<view class="dialog">
			<van-dialog
			  use-slot
			  title="输入溢价"
			  :show="dialogData.show"
			  
			  show-cancel-button
			  @close="closeyijia"
			  @cancel="onDiaClose"
			  @confirm="subDone"
			>
			  <van-cell-group>
			    <van-field
			      :value="dialogData.premium"
			      placeholder="请输入溢价"
			      border
				  type="digit"
			      @change="onMoneyChange"
				  
			    />
			  </van-cell-group>
			</van-dialog>
		</view>
	</view>
</template>

<script>
		import NavBar from "@/components/public/index/NavBar.vue"
		import menuList from "@/components/public/index/menuList.vue"
		import shopList from "@/components/public/index/shopList.vue"
		import OrderList from "@/components/public/order/BaoJia.vue"
		import BanNer from "@/components/public/index/BanNer.vue"
		import uniFab from '@/components/uni-fab/uni-fab.vue';
	export default {
		data() {
			return {
				tabCur: "free",
				horizontal: "left",
				vertical: "bottom",
				direction: "horizontal",
				pattern: {
					color: "#000",
					backgroundColor: "#fff",
					buttonColor:"#007aff",
					selectedColor: '#3c3e49'
				},
				hasorder: false,
				haspay: false,
				textInfo:"",
				orderpay: "",
				orderList: [],
				dialog: {
					show: false,
				},
				dialogData: {
					show: false,
					premium: "",
					orderid: "",
				},
				formData: {},
				orderPrice: "",
				orderInfo: {},
				UserRole: "",
				phoneNumber:["0371-63366168","0371-55951168"],
				orderid: "",
				access_token: "",
			}
		},
		onShow() {
			// this.getSetting()
			this.wxLogin()
			this.getAccess_token()
			this.reflash_token()
		},
		computed: {
			token() {
				return this.$store.state.token
			},
			city() {
				return this.$store.state.cityInfo.city
			},
			classd() {
				if(this.UserRole == 4 && this.token || this.UserRole == 5 && this.token) {
					return "2"
				} else {
					return "1"
				}
			},

			
		},
		onPullDownRefresh() {
			this.getUserAuth()
		},
		components: {
			NavBar,
			menuList,
			shopList,
			uniFab,
			OrderList,
			BanNer,
		},
		onShareAppMessage() {
			return {
				title: '一号加帮',
				path: "/pages/index/index",
			}
		},

		methods: {
			// 有yijia
			doneOrderid( id ) {
				this.dialogData.show = true
				console.log(id);
				this.orderid = id
			},
			// 拨打电话
			makephone() {
				// console.log("1")
				let self = this
				uni.showActionSheet({
					itemList:["代理入住咨询", "用户客服服务"],
					success(res) {
						// console.log(res)
						uni.makePhoneCall({
							phoneNumber: self.phoneNumber[res.tapIndex]
						})
					}
				})
			},
			

			// 获取openid
			wxLogin() {
				let self = this
				uni.login({
					success( res ) {
						// console.log(res);
						if( res.code ) {
							uni.request({
								url: `${self.$Request_Url}/base/openid`,
								method: "POST",
								data: {
									code:res.code
								},
								success( info ) {
									// console.log(info.data.result.access_token)
									let obj = info.data.result
									self.$store.commit("getSid", obj)
									self.getToken(obj.openid)
								}
							})
						} else {
							console.log("登陆失败" + res.errMsg);
						}
					}
				})
			},
			// 获取用户的身份
			async getUserAuth( token ) {
				let self = this
				let res = await this.$Request("POST", "/Index/rank", { token} )
				// console.log(res)
				this.UserRole = res.data.data
				this.$store.commit("getUserRole", this.UserRole)
			},
			// openid获取token
			getToken( openid ) {
				let self = this
				if(openid) {
					uni.request({
						url: `${self.$Request_Url}/Index/usertoken`,
						method: 'POST',
						data: {
							openid
						},
						success: res => {
							//console.log(res);
							let token = res.data.data
							if(token) {
								self.$store.commit("getUserToken", token)
								uni.setStorage({
									key: "miniToken",
									data: res.data.data
								})
								self.getUserAuth( token )
							}
							
						},
						fail: (err) => { console.log(err);},
						
					});
				}
			},
			// 后台获取用户信息
			getUser() {
				let self = this
				//console.log(this.token);
				if(this.token) {
					
					uni.request({
						url: `${self.$Request_Url}/Index/user`,
						method:"POST",
						data: {
							token: self.token
						},
						success( res ) {
							console.log(res);
							if(!res.data.data) {
								uni.removeStorageSync("miniToken")
								self.$store.commit("getUserInfo", "")
								self.$store.commit("getSid", "")
							} else {
								self.$store.commit("getUserInfo", res.data.data)
							}
						}
					})
				} 
			},
			// 报价
			orderChange( item ) {
				console.log(item)
				this.dialog.show = true
				this.formData = item
			},
			// 关闭报价
			close() {
				this.dialog.show = false
			},
			// 报价之前授权
			// 获取订阅消息授权
			getSetting() {
				let self = this
				uni.getSetting({
					withSubscriptions: true,
					success( res ) {
						let isauth = res.authSetting["scope.subscribeMessage"]
						
										// 用户同意授权
										wx.requestSubscribeMessage({
										  tmplIds: [
											  '-fT7TqL9Jza4TUhdfMuh6AC39GxWZj76i2bEpXJsxNk',
											  'fxviPJF4R7JGFzpRR8d2JiZJu7Sucm7_kYzXOGDlv_w',
											  '-EmYCJVoB59CJtCx892Q6HF5D-K9PeTQaWgKDvPS4D4'
											  ],
										  success (res) {
											  // console.log(res);
											  let msg = res.errMsg == "requestSubscribeMessage:ok"
											  if(msg) {
												   self.onConfirm()
											  } else {
												  return false 
											  }
										  },
										  fail(err) {
											  console.log(err);
										  }
										})
						},
				})
				
			},
			// 下单成功后 发送消息
			sendMsg( data ) {
				let self = this
				
				uni.request({
					url: `https://www.awoojing.club/admin/sendMsg`,
					method: "POST",
					data: {
						touser: `${data.openid}`,
						access_token: `${self.access_token}`,
						page: '/pages/index/index',
						lang: 'zh_CN',
						data: {
						  number1: {
							value: `${data.orderid}`
						  },
						  name2: {
							value: `${data.name}`,
						  },
						  amount3: {
							value: `${data.orderprice}元`
						  },
						  thing6: {
							value: `定金${data.imprest}元`
						  },
						  
						},
						templateId: 'fxviPJF4R7JGFzpRR8d2JiZJu7Sucm7_kYzXOGDlv_w',
						
					},
					success( res ) {
						console.log(res);
					},
					fail( err ) {
						console.log(err);
					}
				})
				
					
			},
			//  进入当前页面后获取access_token
			getAccess_token() {
				let self = this
				uni.request({
					url: "https://www.awoojing.club/admin/getAccess_token",
					method:"POST",
					data: {},
					success(res) {
						// console.log(res);
						if(res.data.code == 200) {
							self.access_token = res.data.data
						}
					}
				})
				
			},
			// 定时刷新access_token
			reflash_token() {
				let self = this 
				setInterval(() => {
					self.getAccess_token()
				}, 1000 * 60 * 10)
			},
			// 提交报价
			async onConfirm() {
				this.formData.master = this.token
				let data = this.formData
				let self = this
				// console.log(data)
				if(Number(data.imprest) >= Number(data.orderprice)) {
					uni.showToast({
						title: "预付金超出",
						icon: "loading"
					})
					this.dialog.show = false
					this.formData = {}
					this.$refs.order.getAllOrder()
					return false
				} else if( !data.orderprice) {
					uni.showToast({
						title: "请输入报价",
						icon: "loading"
					})
					this.dialog.show = false
					this.formData = {}
					return false
				} else if( !data.imprest) {
					uni.showToast({
						title: "请输入预付金额",
						icon: "loading"
					})
					this.dialog.show = false
					this.formData = {} 
					return false
				} else {
					let datas = {
						master: this.token,
						orderid: this.formData.orderid,
						orderprice: this.formData.orderprice,
						imprest : this.formData.imprest
					}
					let res = await this.$Request("POST", "/order/offerprice", datas)
					console.log(res);
					if(res.data.code == 202 ) {
						uni.showToast({
							title: "报价成功",
							icon: "success"
						})
						self.sendMsg({
							orderid: self.formData.orderid,
							name: res.data.data.name,
							orderprice: self.formData.orderprice,
							imprest: self.formData.imprest,
							openid: res.data.data.openid
						})
					}
					this.dialog.show = false
					this.formData = {}
					this.$refs.order.getAllOrder()
				}	
			},
			priceChange(e) {
				let reg = /\D/g
				this.formData.orderprice = e.detail.replace("reg", "")
			},
			imprestChange( e ) {
				let reg = /\D/g
				this.formData.imprest = e.detail.replace("reg", "")
			},
			// 获取用户是否有待支付的订单
			async getOrder(  ) {
				let self = this
				if(this.token) {
					let res = await this.$Request("POST", "/Index/indentlist",{ token: this.token, status: '3' })
					let ret = await this.$Request("POST", "/Index/indentlist",{ token: this.token, status: '6' })
					if(res.data.data ) {
						this.hasorder = true
						this.textInfo = `${res.data.data.length}笔订单待支付`
					} else if(ret.data.data){
						this.haspay = true
						this.orderpay = `${ret.data.data.length}笔订单待结算`
					}
						
				}
			},
			// 去登录
			login() {
				uni.switchTab({
					url: "/pages/my/my"
				})
			},
			// 点击tab
			onTabClick( e ) {
				// console.log(e);
			},
			// 关闭dialog
			closeyijia() {
				this.dialogData.show = false
				// this.dialogData.premium = ""
			},
			onDiaClose(e) {
				this.dialogData.show = false
				this.dialogData.premium = ""
				this.orderid = ""
				uni.showToast({
					title: "取消操作",
					icon: "loading"
				})
			},
			// 输入框变化
			onMoneyChange(e) {
				this.dialogData.premium = e.detail
				console.log(this.dialogData.premium);
			},
			// 接收orderid
			doneServer( orderid ) {
				this.orderid = orderid
				this.dialogData.show = true
				console.log( this.orderid );
			},
			// 提交完成订单
			async subDone() {
				let orderid = this.orderid
				let premium = this.dialogData.premium
				console.log(orderid, premium);
				let self = this
				let ret = await self.$Request("POST",'/Index/orderfinish', { orderid, premium, token: self.token })
				if(ret.data.code == 202) {
					uni.showToast({
						title: "服务完成",
						icon: "success"
					})
					this.dialogData.show = false
					this.orderid = ""
					this.dialogData.premium = ""
				}
			},
			
			
		}
	}
</script>

<style lang="scss" scoped>
.indexpage {
	width: 100%;
	box-sizing: border-box;
	overflow-x: hidden;
	background-color: rgb(241,238,246);
	.makephone {
		position: fixed;
		right: 30rpx;
		bottom: 120rpx;
		text {
			font-size: 70rpx;
			color: orange;
		}
	}
	.sban {
		width: 100%;
		box-sizing: border-box;
		padding: 10rpx 20rpx;
		text-align: center;
		image {
			width: 710rpx;
			height: 160rpx;
		}
	}
	.kehu {
		width: 100%;
		.tabCard {
			width: 100%;
			display: flex;
			align-items: center;
			.tab-item{
				width: 50%;
				padding: 10rpx;
				text-align: center;
			}
			.active {
				background-color: #007AFF;
				color: #fff;
			}
		}
		.list-free {
			width: 100%;
			.good {
				width: 100%;
				box-sizing: border-box;
				text-align: center;	
				font-size: 40rpx;
				color: green;
				font-weight: bolder;
				line-height: 60rpx;
			}
		}
	}
}
</style>
